<?php
/**
 * Created by PhpStorm.
 * User: zhanglihe
 * Date: 2018/6/4
 * Time: 上午10:06
 */

namespace Modules\Token;

use Modules\Token\Driver\StorageDB;
use Modules\Token\Driver\StorageInterface;
use Modules\Token\Driver\StorageRedis;

class Token
{
    /**
     * 存储类
     *
     * @var StorageInterface
     */
    protected $storageDriver;

    protected $options = [];

    public $tokenData = [];

    public function __construct()
    {
        $this->options = [
            // 存储类型，可选择[redis, db]
            'driver' => env('TOKEN_DRIVER', 'redis'),

            // token有效期
            'minutes' => env('TOKEN_EXPIRE_MINUTES', 600),

            // 如果是db存储，指定存储表名
            'table' => env('TOKEN_TABLE', 'token'),

            // 生成token的盐值
            'salt' => env('TOKEN_SALT', 'somestringkeyfortokensave'),
        ];
    }

    public function generate($publicKey = '', Array $data = [])
    {
        $token = md5($this->options['salt'] . '-' . microtime(true) . $publicKey . '-' . rand(10000, 99999));
        $this->put($token, $data);
        $this->tokenData = $data;
        return $token;
    }

    public function has($token)
    {
        if ($this->getStorage()->has($token)) {
            $this->get($token);
            return true;
        }
        return false;
    }

    public function get($token)
    {
        $data = $this->getStorage()->get($token);
        $this->tokenData = $data;
        return $data;
    }

    public function data($key = '')
    {
        if (!$this->tokenData) {
            return null;
        }
        if ($key && isset($this->tokenData[$key])) {
            return $this->tokenData[$key];
        }
        return $this->tokenData;
    }

    public function forget($token)
    {
        $this->getStorage()->forget($token);
    }

    public function flushExpired()
    {
        $this->getStorage()->flushExpired();
    }

    public function all()
    {
        return $this->getStorage()->all();
    }

    protected function put($token, $data)
    {
        $this->getStorage()->put($token, $data);
    }

    protected function getStorage()
    {
        if ($this->storageDriver) {
            return $this->storageDriver;
        }
        $driver = $this->options['driver'];
        if ($driver == 'redis') {
            $this->storageDriver = new StorageRedis($this->options);
        }
        if ($driver == 'db') {
            $this->storageDriver = new StorageDB($this->options);
        }
        return $this->storageDriver;
    }

}